package com.wimcorp.magic.dataloader.costs;

import java.util.HashSet;

import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.ui.CellPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.wimcorp.magic.data.CostData;
import com.wimcorp.magic.input.CostInput;

public class CostWidget {

	private String name;
	private String config ="";
	private CellPanel configurationPanel = new VerticalPanel();

	public CostWidget(CostInput cost) {
		this.name = cost.toString();
	}

	public static CostWidget createCostWidget(CostInput cost) {
		switch (cost) {
		case MANA_COST:
			return new ManaCostWidget(cost);
		case PAYLIFE :
			return new PayLifeWidget(cost);
		case RETURN_COST :
			return new ReturnCostWidget(cost);
		default:
			return new CostWidget(cost);
		}
	}
	
	protected JSONArray getSelectedItems(ListBox listbox) {
		JSONArray selected = new JSONArray();
		if (listbox.isMultipleSelect()) {
			HashSet<Integer> indexes = new HashSet<Integer>();
			while (listbox.getSelectedIndex() >= 0) {
				int index = listbox.getSelectedIndex();
				listbox.setItemSelected(index, false);
				String selectedElem = listbox.getValue(index);
				selected.set(indexes.size(), new JSONString(selectedElem));
				indexes.add(index);
			}
			for (Integer index : indexes) {
				listbox.setItemSelected(index, true);
			}
		} else {
			selected.set(0, new JSONString(listbox.getValue(listbox.getSelectedIndex())));
		}
		return selected;
	}

	protected void loadListBox(ListBox listbox, JSONValue json) {
		if (json != null) {
			String value = toString(json);
			if (value != null) {
				for (int i = 0; i < listbox.getItemCount(); i++) {
					if (value.equals(listbox.getItemText(i))|| value.equals(listbox.getValue(i))) {
						listbox.setItemSelected(i, true);
					}
				}
			}
		}
	}
	
	protected String toString(JSONValue value) {
		if (value instanceof JSONArray) {
			return ((JSONArray) value).get(0).toString().replace("\"", "");
		} else {
			return value.toString().replace("\"", "");
		}
	}
	

	public CellPanel getConfigurationPanel() {
		return configurationPanel;
	}
	
	public void load(CostData cost) {

	}

	public String getName() {
		return name;
	}
	
	public String getConfig(){
		return config;
	}
	
	

}
